/**
 * 
 */
package com.douyu.ocean.recom.platform.api.component.bypass;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
 * 根据uid取模分流组件
 * 
 * 举例表达式  10:10:80 表示，3种结果，分别命中几率是 10% ,10%, 80% 总和需要满足 加起来是100;
 * 
 * uid对100取模，然后看落到哪个区间
 * 
 * 
 * 
 * 
 * @author leiruiqi
 *
 */
@Component
public class MoldUserBypassComponent extends BypassComponent {
	
	private Map<String,List<Integer>> expressionListMap = new HashMap<String,List<Integer>>();

	/* (non-Javadoc)
	 * @see com.douyu.ocean.recom.platform.api.component.BypassComponent#getComponentKey()
	 */
	@Override
	public String getComponentKey() {
		// TODO Auto-generated method stub
		return "mold";
	}

	/* (non-Javadoc)
	 * @see com.douyu.ocean.recom.platform.api.component.BypassComponent#getByPassResultNum(java.lang.String, java.lang.Long)
	 */
	@Override
	public int getByPassResultNum(String expression, Long uid) {
		
		if(!checkExpression(expression)){
			throw new RuntimeException();
		}
		
		List<Integer> list = getIntervalArray(expression);
		
		Long value = uid%100;
		for(int i=0;i<list.size();i++){
			int temp = list.get(i);
			
			if(value.intValue()<=temp){
				return i;
			}
		}
		return list.size();
		
	}
	
	

	@Override
	public boolean checkExpression(String expression) {
		// TODO Auto-generated method stub
		return true;
	}
	
	private List<Integer> getIntervalArray(String expression){
		if(expressionListMap.containsKey(expression)){
			return expressionListMap.get(expression);
		}
		String[] abc = StringUtils.split(expression, "|");
		List<Integer> list = new ArrayList<Integer>();
		int temp = 0;
		for(int i=0;i<abc.length;i++){
			Integer a = Integer.valueOf(abc[i]);
			temp+=a;
			list.add(temp);
		}
		expressionListMap.put(expression, list);
		return list;
	}

}
